package com.feihong.txgw.ui.fragment.recharge;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.recharge.PhoneRechargeAdapter;
import com.feihong.txgw.inter.contract.recharge.RechargeContract;
import com.feihong.txgw.tx_precenter.RechargeMainPrecenter;
import com.feihong.txgw.ui.activity.order.PayActivity;
import com.feihong.txgw.global.GlobalContents;
import com.feihong.txgw.json.recharge.PhoneLocationInfo;
import com.feihong.txgw.json.recharge.SubmitOrderInfo;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.ui.mvp.BaseMVPCompatFragment;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 2017/6/13
 * 张鹏
 * 流量购买
 */
public class GPRSRechargeFragment extends BaseMVPCompatFragment<RechargeContract.AbRechargeMainPrecenter> implements RechargeContract.IRechargeMainView {

    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.grid)
    GridView grid;
    @BindView(R.id.yunyings)
    TextView yunyings;
    @BindView(R.id.yys_content)
    TextView yysContent;
    @BindView(R.id.btn_ljcz)
    Button btnLjcz;
    /**
     * -1代表没有选中套餐
     */
    private int usePosition = -1;
    private PhoneRechargeAdapter myAdapter;
    private String phoneNum;
    private int status;
    private int icp_type;
    private List<PhoneLocationInfo.GoodsDataBean> data;
    PhoneLocationInfo info;

    public static GPRSRechargeFragment newInstance(String tabName) {
        GPRSRechargeFragment gprsRechargeFragment = new GPRSRechargeFragment();
        gprsRechargeFragment.tag = tabName;
        return gprsRechargeFragment;
    }
    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.fragment_recharge_phone;
    }

    private ArrayList<String> list = new ArrayList<String>();
    private ArrayList<String> gprsList = new ArrayList<String>();

    @Override
    public void initView() {
        super.initView();

        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                phoneNum = edPhone.getText().toString().trim();

                if (!phoneNum.isEmpty() && RegexUtils.isMobileSimple(phoneNum)) {
                    // 将选中的position传给adapter
                    myAdapter.changeState(position);

                    // 需要使用的position
                    usePosition = position;
                } else {
                    KeyboardUtils.hideSoftInput(_mActivity);
                    ToastUtils.getInstance().showShortToast("请先输入11位手机号码");
                }

            }
        });

        SpannableString hintText = new SpannableString("请输入手机号码");
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(15, true);
        hintText.setSpan(ass, 0, hintText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        edPhone.setHint(hintText);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        //页面显示才能触发
        //绑定View
        initView();

        //绑定数据
        bindData();
    }

    @Override
    public void bindData() {
        list.add("5");
        list.add("10");
        list.add("15");
        list.add("30");
        list.add("50");

        gprsList.add("30M");
        gprsList.add("100M");
        gprsList.add("200M");
        gprsList.add("500M");
        gprsList.add("1024M");
        myAdapter = new PhoneRechargeAdapter(_mActivity, list, gprsList);
        grid.setAdapter(myAdapter);
        // EditText变化监听
        edPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 变化前

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 变化中
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 变化后
                phoneNum = edPhone.getText().toString().trim();
                if (phoneNum.length() == 11) {
                    hideSoftInput();
                    if (!RegexUtils.isMobileExact(phoneNum)) {
                        showSystemToast("您输入的手机号格式有误");
                        return;
                    }
                    showProgressDialog("请稍等...");
                    getGoods();
                } else {
                    // 不做操作
                    yunyings.setVisibility(View.GONE);
                    yysContent.setVisibility(View.GONE);
                    // 将选中的position传给adapter
                    myAdapter.changeState(-1);

                    // 需要使用的position
                    usePosition = -1;
                }
            }
        });
    }

    private void getGoods() {
        mPrecenter.loadOperator(GlobalContents.RECHARGE_GPRS_TYPE,phoneNum);
    }

    private void getPhoneData() {
        list = new ArrayList<String>();
        gprsList = new ArrayList<String>();
        data = info.getData().getGoods();
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                list.add(data.get(i).getOriginal_price());
                gprsList.add(data.get(i).getGoods_name());
            }
            myAdapter = new PhoneRechargeAdapter(_mActivity, list, gprsList);
            grid.setAdapter(myAdapter);
        }
    }

    @OnClick(R.id.btn_ljcz)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_ljcz:
                //立即充值
                phoneNum = edPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phoneNum)) {
                    showSystemToast("请输入手机号码");
                    return;
                }
                if (!RegexUtils.isMobileExact(phoneNum)) {
                    showSystemToast("您输入的手机号格式有误");
                    return;
                }
                if (status != 1) {
                    showDialog(null, "请检查您输入的手机号码是否正确以及网络连接情况");
                    return;
                }
                if (usePosition == -1) {
                    showSystemToast("请先选择充值数目");
                    return;
                }
                subToNet();
                break;
            default:
                break;
        }
    }

    private void subToNet() {
        showProgressDialog("正在提交订单...");
        mPrecenter.submitRechargeOrder(GlobalContents.RECHARGE_GPRS_TYPE,phoneNum,GlobalContents.TERMINAL_TYPE,data.get(usePosition).getGoods_id());
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void loadOperatorsResult(PhoneLocationInfo resultInfo) {
        info = resultInfo;
        if ("200".equals(info.getCode())) {
            status = info.getData().getIcp_info().getStatus();
            if (status == 1) {
                yunyings.setVisibility(View.VISIBLE);
                yysContent.setVisibility(View.VISIBLE);
                String str = info.getData().getIcp_info().getProvince() + "   "
                        + info.getData().getIcp_info().getCity() + "   " + info.getData().getIcp_info().getSupplier();
                yysContent.setText(str);
                // 根据运营商类型修改默认数据
                icp_type = info.getData().getIcp_info().getIcp_type();
                getPhoneData();
            } else {
                showSystemToast("获取手机归属地信息失败");
            }
        } else {
            showSystemToast("获取手机归属地信息失败");
        }
    }

    @Override
    public void submitRechargeOrderResult(SubmitOrderInfo submitOrderInfo) {

        // 订单号
        String order_id = submitOrderInfo.getOrder_sn();
        // 价格
        String price = submitOrderInfo.getPrice();
        Intent intent = new Intent(getActivity(), PayActivity.class);
        // 订单号
        intent.putExtra(PayActivity.INTENT_ORDER_ID, order_id);
        // 价格
        intent.putExtra(PayActivity.INTENT_PRICE, price);
        intent.putExtra(PayActivity.INTENT_TITLE, phoneNum + " 购买流量");
        intent.putExtra(PayActivity.INTENT_PAY_TYPE, PayActivity.PAY_TYPE_PHONE_GPRS);
        startActivity(intent);
        getActivity().finish();
    }


    @Override
    public void loadDataComplated() {
        dismissProgressDialog();
    }

    @Override
    public void loadDataError() {
        dismissProgressDialog();
        showDialog(null,getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return RechargeMainPrecenter.create();
    }
}
